<template>
  <t-dialog width="80%" header="修改护理计划" :visible.sync="visiable" :confirmOnEnter="true" @close="closeEdit"
    @confirm="saveProject">
    <t-space direction="vertical" style="width: 100%">
      <!-- rule:绑定表单每一项的校验规则 -->
      <t-form :data="addFormData" labelWidth="calc(8em + 24px)" layout="vertical" :rules="addFormRule"
        ref="nusrong_plan_form" @reset="onReset" @submit="saveProjectToDB">
        <t-form-item label="护理计划名称" name="planName">
          <t-input v-model="addFormData.planName" placeholder="请输入护理计划名称"></t-input>
        </t-form-item>
        <t-form-item label="排序" name="sortNo">
          <t-input v-model="addFormData.sortNo" type="number" placeholder="请输入护理计划排序"></t-input>
        </t-form-item>
        <t-form-item label="状态" name="status">
          <t-radio-group v-model="addFormData.status">
            <t-radio v-for="(item, index) in statusOptions" :key="index" :value="item.value">{{ item.label }}</t-radio>
          </t-radio-group>
        </t-form-item>
        <t-form-item label="选择护理项目" name="projects">
          <!-- 表格显示护理项目列表 -->
          <t-table bordered row-key="index" :data="projectList" :columns="add_columns">
            <template #execute_cycle="{ row }">
              <span style="color:red;display: inline-block;" v-if="row.noFinish">*</span>
              <t-select v-model="row.executeCycle" width="200px" id="cycle">
                <t-option :key="index" v-for="(item, index) in cycleOptions" :label="item.label" :value="item.value" />
              </t-select>
            </template>
            <template #execute_frequency="{ row }">
              <span style="color:red;display: inline-block;" v-if="row.noFinish">*</span>
              <t-input type="number" v-model="row.executeFrequency" placeholder="请输入执行频次"></t-input>
            </template>
            <template #execute_time="{ row }">
              <span style="color:red;display: inline-block;" v-if="row.noFinish">*</span>
              <t-time-picker v-model="row.executeTime" format="HH:mm" />
            </template>
          </t-table>
        </t-form-item>
      </t-form>
    </t-space>
  </t-dialog>
</template>
<script setup lang="js">
import { ref, onMounted, watch } from 'vue'
import add_columns from '../add_columns'
import { getList } from '@/api/nursing_project_api'
import { MessagePlugin } from 'tdesign-vue-next'
import { saveNursingPlan } from '@/api/nursing_plan_api'
const props = defineProps(['visiable', 'addFormData'])
const emit = defineEmits(['closeEditDialog', 'refresh'])

// 需要提交的数据
const projectList = ref([])
// 表单对象
const nusrong_plan_form = ref(null)
// 启用禁用下拉框
const statusOptions = ref([
  { label: "启用", value: 1 },
  { label: "禁用", value: 0 }
])

const cycleOptions = ref([
  { label: "天", value: 0 },
  { label: "周", value: 1 },
  { label: "月", value: 2 }
])

const closeEdit = () => {
  emit('closeEditDialog')
}

// 侦听的是回显的数据
watch(() => props.addFormData,
  (newVal) => {
    // console.log("有数据了。。。", newVal.nursingProjectPlans.length, projectList.value);

    if (newVal && newVal.nursingProjectPlans) {
      // 合并props.addFormData到projectList.value
      for (let index = 0; index < newVal.nursingProjectPlans.length; index++) {
        const element = newVal.nursingProjectPlans[index];
        findAndUpdate(element)
      }
    }


    // console.log(projectList.value);
  })

// 从集合projectList.value中查找记录，根据项目id查找，找到之后修改
// item =nursingProjectPlans [{"id": 1674,"projectId": 6,"executeTime": "02:00","executeCycle": 1,"executeFrequency": 3}]
const findAndUpdate = (item) => {
  if (projectList && projectList.value) {
    for (let i = 0; i < projectList.value.length; i++) {
      const element = projectList.value[i];

      if (element.id == item.projectId) {
        element.executeCycle = item.executeCycle
        element.executeFrequency = item.executeFrequency
        element.executeTime = item.executeTime
      }

    }
  }

}



// 只执行一次
onMounted(() => {
  loadList({ pageSize: 100 })
})

// 校验规则
const addFormRule = ref({
  planName: [
    {
      required: true,
      message: "护理计划名称是必填项"
    }
  ],
  sortNo: [
    {
      required: true,
      message: "排序号是必填项"
    }
  ],
  status: [
    {
      required: true,
      message: "状态是必填项"
    }
  ]
})

// 加载项目列表
const loadList = async (params) => {
  const resp = await getList(params)
  console.log("列表数据：", resp);

  projectList.value = resp.records

  // 添加表格项目中验证标志
  for (let index = 0; index < projectList.value.length; index++) {
    const element = projectList.value[index];
    element.noFinish = false
  }
}

// 点击对话框的确定按钮，手动触发表单的提交方法
// const saveProject = () => {
//   nusrong_plan_form.value.submit()
// }
// // 保存护理计划 
// const saveProjectToDB = ({ validateResult, firstError }) => {
//   // 统计不完整的行数
//   let count = 0
//   // 循环检查
//   // 一行数据只要有一个填写了，其它两个必须填写，标志打开
//   for (let index = 0; index < projectList.value.length; index++) {
//     let element = projectList.value[index];

//     // 未填写的字段值是undefined,长度是9,3个都不填，长度是27
//     // 3个都填写，最少长度是7，最大是8
//     let length = (element.executeCycle + "").length + (element.executeFrequency + "").length + (element.executeTime + "").length

//     if (length != 7 && length != 8 && length != 27) {
//       element.noFinish = true
//       count++
//     }
//   }

//   // true表示校验通过
//   if (validateResult === true && count === 0) {
//     let listData = []
//     // 填写了数据的表格行才提交
//     for (let index = 0; index < projectList.value.length; index++) {
//       let element = projectList.value[index];
//       if ((element.executeCycle + "").length > 0 && (element.executeCycle + "").length != 9) {
//         listData.push(element)
//       }
//     }

//     addFormData.value.nursingProjectPlans = listData

//     console.log("提交的数据：", addFormData.value);

//     save(addFormData.value)

//   } else {
//     if (firstError) {
//       MessagePlugin.warning(firstError);
//     }
//     if (count > 0) {
//       MessagePlugin.warning(count + "行表单数据不完整，查看表格的红色*号标记")
//     }
//   }
// }

// const save = async (obj) => {
//   await saveNursingPlan(obj)

//   // 关闭对话框
//   emit('closeAddDialog')
//   // 清空数据

//   // 刷新列表
//   emit('refresh')
// }


</script>

<style lang="css" scoped>
#cycle {
  display: inline-block !important;
}
</style>